/**
 * @author zhoushengtao
 * @since 2012-9-7 下午7:54:34
 */

package com.stchou.superbrowser.ui.adapter;

import com.stchou.superbrowser.activity.R;
import com.stchou.superbrowser.db.bean.website;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WebsiteListviewAdapter extends BaseAdapter
{

    private List<website> m_websiteLists;
    private Context m_context;
    // 当前的缓存
    private Map<Integer, View> viewMap = new HashMap<Integer, View>();

    public WebsiteListviewAdapter(Context m_context, List<website> m_websiteLists)
    {
        this.m_context = m_context;
        this.m_websiteLists = m_websiteLists;
    }

    @Override
    public int getCount()
    {
        return m_websiteLists.size();
    }

    @Override
    public Object getItem(int position)
    {
        return m_websiteLists.get(position);
    }

    @Override
    public long getItemId(int position)
    {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        // 先从缓存里面读取
        ViewHolder holder = null;
        View view;

        if (viewMap.get(position) == null)
        {
            view = newView();
            holder = new ViewHolder();
            holder.mTitle = (TextView)view.findViewById(R.id.website_name);
            holder.mSite = (TextView)view.findViewById(R.id.website_addr);

            viewMap.put(position, view);
            view.setTag(holder);
        }
        else
        {
            view = viewMap.get(position);
            holder = (ViewHolder)view.getTag();
        }

        website site = m_websiteLists.get(position);
        holder.mTitle.setText(site.getName());
        holder.mSite.setText(site.getWebsite());

        return view;
    }

    private View newView()
    {
        LayoutInflater inflater = (LayoutInflater)m_context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemView = inflater.inflate(R.layout.listview_item, null);
        return itemView;
    }

    static class ViewHolder
    {
        TextView mTitle;
        TextView mSite;
    }
}
